<template>
  <div id="aCoursesList" class="bg-fa of">
    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps
      :active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px;"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="提交审核" />
    </el-steps>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input
          v-model="courseInfo.title"
        />
      </el-form-item>

      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select
          @change="subjectLevelOneChanged"
          v-model="courseInfo.subjectParentId"
          placeholder="请选择"
        >
          <el-option
            v-for="subject in subjectNestedList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="请选择">
          <el-option
            v-for="subject in subSubjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
          v-model="courseInfo.description">
        </el-input>
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload
          class="avatar-uploader"
          action="http://localhost/api/oss/file/upload?module=cover"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="courseInfo.cover"
            style="width: 400px; height: 200px"
            :src="courseInfo.cover"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />
        元
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">
          保存并下一步
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import courseApi from '@/api/course';
import subjectApi from '@/api/subject';
import cookie from "js-cookie";

const defaultForm = {
  title: '',
  subjectId: '',
  teacherId: '',
  lessonNum: 0,
  description: '',
  cover: 'https://srb-file202183.oss-cn-beijing.aliyuncs.com/cover/default.jpg',
  price: 0,
  type: 0
}

export default {
  data() {
    return {
      BASE_API: process.env.VUE_APP_BASE_API,
      subjectNestedList: [], //一级分类列表
      subSubjectList: [], //二级分类列表
      courseInfo: defaultForm, //课程信息
      saveBtnDisabled: false // 保存按钮是否禁用
    }
  },

  watch: {
    $route(to, from) {
      console.log('watch $route')
      this.init()
    }
  },

  created() {
    console.log('info created')
    this.init()
  },

  methods: {
    init() {
      if (this.$route.params && this.$route.params.id && this.$route.params.id !== "-1") {
        const id = this.$route.params.id
        console.log(id)
        // 根据id获取课程基本信息
        this.fetchCourseInfoById(id)
      } else {
        this.courseInfo = { ...defaultForm }
        var jsonStr = cookie.get('fuyao_ucenter')
        if (jsonStr) {
          console.log('jsonStr' + JSON.stringify(jsonStr))
          this.myInfo = JSON.parse(jsonStr)
          this.courseInfo.teacherId = this.myInfo.id
        }
      }
      // 初始化分类列表
      this.initSubjectList()
    },

    fetchCourseInfoById(id) {
      courseApi.getCourseInfoById(id).then(response => {
        this.courseInfo = response.data.data.item
        console.log(this.courseInfo)
      })
    },

    initSubjectList() {
      subjectApi.getNestedTreeList().then(response => {
        this.subjectNestedList = response.data.data.list
      })
    },

    next() {
      console.log('next')
      this.saveBtnDisabled = true
      if (!this.courseInfo.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },

    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 保存
    saveData() {
      courseApi
        .saveCourseInfo(this.courseInfo)
        .then(response => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          return response // 将响应结果传递给then
        })
        .then(response => {
          this.$router.push({
            path: '/ucenter/chapter/' + response.data.data.courseId
          })
        })
        .catch(response => {
          this.$message({
            type: 'error',
            message: response.message
          })
        })
    },

    updateData() {
      this.$router.push({ path: '/ucenter/chapter/' + this.courseInfo.id })
    },

    subjectLevelOneChanged(value) {
      console.log(value)
      for (let i = 0; i < this.subjectNestedList.length; i++) {
        if (this.subjectNestedList[i].id === value) {
          this.subSubjectList = this.subjectNestedList[i].children
          this.courseInfo.subjectId = ''
        }
      }
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>
